/**
 *
 * ......................我佛慈悲.......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG....................
 *         CSDN博客:http://blog.csdn.net/song5347
 *       github地址:https://github.com/lingsuiderongyan
 *             邮箱:lingsuiderongyan@163.com
 */
//微博配图视图
import UIKit
import SDWebImage

//重用标记
private let StatusPictureViewCellIdentifier = "StatusPictureViewCellIdentifier"
//每项间距
let itemMargin: CGFloat = 5
//每项宽度
let itemWidth = (ScreenWidth - 2 * StatusTableViewCellMargin - 2 * itemMargin) / 3

class LSStatusPictureView: UICollectionView {
    
    var picUrls: [LSStatusPictureInfo]? {
        didSet {
            
            //显示几张图片
            //messageLabel.text = "\(picUrls?.count ?? 0)"
            
            //根据配图的个数计算大小
            let size = calsSizeWithCount(picUrls?.count ?? 0)
            //更新约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            //绑定数据
            self.reloadData()
        }
    }
    
    //显示配图个数
    private lazy var messageLabel: UILabel = UILabel(fontSize: 20, textColor: UIColor.whiteColor())
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        
        //设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        //垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件设置约束
    private func setupUI() {
        
        //注册cell
        registerClass(LSStatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewCellIdentifier)
        //设置数据代理
        dataSource = self
        
        //设置代理
        delegate = self
        
        //添加控件
        addSubview(messageLabel)
        
        //布局
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
        
    }
    
    //通过配图个数计算配图的大小
    private func calsSizeWithCount(count: Int) -> CGSize {
        
        //列数
        let cols = count > 3 ? 3 : count
        //行数
        let rows = (count - 1) / 3 + 1
        //宽度
        let currentWidth = itemWidth * CGFloat(cols) + CGFloat(cols - 1) * itemMargin
        //高度
        let currentHeight = itemWidth * CGFloat(rows) + CGFloat(rows - 1) * itemMargin
        
        return CGSize(width: currentWidth, height: currentHeight)
    }
    
}

//  MARK:   - 实现UICollectionViewDataSource的协议
extension LSStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewCellIdentifier, forIndexPath: indexPath) as! LSStatusPictureViewCell
        
        //设置模型数据
        cell.picInfo = picUrls![indexPath.item]
        
        return cell
    }
    
    
}

//MARK: - 自定义配图cell
class LSStatusPictureViewCell: UICollectionViewCell {
    
    //MARK: - 绑定数据
    var picInfo: LSStatusPictureInfo? {
        didSet {
            if let url = picInfo?.thumbnail_pic {
                imageView.sd_setImageWithURL(NSURL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                
//                if url.hasSuffix(".gif") {
//                    gifImageView.hidden = false
//                } else {
//                    gifImageView.hidden = true
//                }
                gifImageView.hidden = !url.hasSuffix(".gif")
            }
        }
    }
    
    //MARK: - 懒加载控件
    private lazy var imageView: UIImageView = {
        
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        
        //修改显示模型为等比填充,保证图片比例不变
       view.contentMode = UIViewContentMode.ScaleAspectFill
        //多余图片剪切掉
        view.clipsToBounds = true
        return view
        
    }()
    
    //MARK: - GIF图片视图
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //添加控件设置约束
    private func setupUI() {
        
        //添加控件
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        //设置约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imageView)
            make.bottom.equalTo(imageView)
        }
        
    }
}
















